﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Collections.Specialized;
using System.Configuration;
using System.Web.Caching;
using System.Data;
using System.Configuration.Provider;
using System.Text.RegularExpressions;


namespace MyWebPagesStarterKit.Rewriter
{
    /// <summary>
    /// Contains methods to rewrite sections back to a page.
    /// </summary>
    public class SectionRewriter : ISectionRewriter
    {
        /// <summary>
        /// Section Rewriter
        /// Checks url for a string that are equal to a rewrite string.
        /// </summary>
        /// <param name="requestedPath">The current url</param>
        /// <param name="app">HttpApplication</param>
        protected override void Rewrite(string requestedPath, System.Web.HttpApplication app)
        {
            NameValueCollection config = (NameValueCollection)ConfigurationManager.GetSection("rewrite/sections");
            if (config == null) //Check if rewrite section exits
                return;

            if (requestedPath.EndsWith(".aspx"))
            {
                bool rebase = true;
                if (app.Context.User.Identity.IsAuthenticated)
                    rebase = false;

                string[] keys = config.AllKeys;
                string val = null;
                string id = null;

                foreach (string key in keys)
                {
                    if (requestedPath.Contains(key))
                    {
                        val = config[key];

                        List<ISection> sections = SectionLoader.GetInstance().LoadSections(val);

                        foreach (ISection section in sections)
                        {
                            if (section.GetType().Name == val)
                            {
                                foreach (DataRow row in section.Entries.Rows)
                                {

                                    if (row["RewriteUrl"].ToString().ToLower() == requestedPath.Substring(requestedPath.LastIndexOf('/') + 1).ToLower())
                                    {
                                        id = row["Guid"].ToString();
                                        app.Context.RewritePath(string.Format("/default.aspx?pg={0}&details={1}", section.PageID, id), rebase);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
           
        }

        /// <summary>
        /// Get the rewrite string from web.config
        /// </summary>
        /// <param name="sectionName">The section name</param>
        /// <returns>If found, the prefix, else the sections name</returns>
        public static string GetPrefix(string sectionName)
        {
            NameValueCollection config = (NameValueCollection)ConfigurationManager.GetSection("rewrite/sections");
            if (config == null)
                return sectionName;

            foreach (string key in config.AllKeys)
            {
                if (config[key] == sectionName)
                {
                    sectionName = key;
                    break;
                }
            }
            return sectionName;
        }
    }
}
